package proj2501.simple_module;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import proj2501.lib.RefreshingPanel;

class P001BouncingBalls extends RefreshingPanel {
	private List<Ball> balls = new LinkedList<Ball>();
	public P001BouncingBalls() {
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				super.mouseReleased(e);
//				Ball ball = new Ball();
//				ball.x = e.getX() - ball.width / 2;
//				ball.y = e.getY() - ball.height / 2;
//				balls.add(ball);
				addBall(5);
			}
		});
//		balls.add(new Ball());
		addComponentListener(new ComponentAdapter() {
			private boolean initDone;
			@Override
			public void componentResized(ComponentEvent e) {
				super.componentResized(e);
				int width = e.getComponent().getWidth();
				int height = e.getComponent().getHeight();
				if (initDone == false && width != 0 && height != 0) {
					addBall(20);
					initDone = true;
				}
			}
		});
	}
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		for (Ball ball: balls) {
			ball.paint(g);
			ball.move();
		}
		String s = "Frame Count: " + getFrameCount();
		g.drawString(s, 5, 15);
	}
	
	private Random random;
	private void addBall() {
		if (random == null) {
			random = new Random();
		}
		Ball ball = new Ball();
		ball.x = random.nextInt(getWidth()) - ball.width / 2;
		ball.y = random.nextInt(getHeight()) - ball.height / 2;
		balls.add(ball);

	}
	private void addBall(int numBalls) {
		for (int i = 0; i < numBalls; i++) {
			addBall();
		}
		System.out.println(numBalls + " balls added. (Total: " + balls.size() + ")");
	}
	
	private class Ball {
		public int width = 64;
		public int height = width;
		public int x;
		public int y;
		public int dx = 4;
		public int dy = dx;
		
		public void paint(Graphics g) {
			g.drawOval(x, y, width, height);
		}
		
		public void move() {
			Dimension size = P001BouncingBalls.this.getSize();
			int fieldWidth = size.width - width;
			int fieldHeight = size.height - height;
			x += dx;
			y += dy;
			if (x < 0 && dx < 0 || fieldWidth <= x && 0 < dx) {
				dx = -dx;
			}
			if (y < 0 && dy < 0 || fieldHeight <= y && 0 < dy) {
				dy = -dy;
			}
		}
	}
}
